<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
  <title>AMap JS API v2 Demo (Proxy-secured)</title>
  <style>
    html, body { height: 100%; margin: 0; }
    #app { display: flex; flex-direction: column; height: 100%; }
    header { padding: 10px 12px; border-bottom: 1px solid #eee; font-weight: 600; }
    #map { flex: 1; }
    .toolbar { display: flex; gap: 8px; padding: 8px 12px; border-top: 1px solid #eee; }
    input, button, select { padding: 6px 8px; font-size: 14px; }
    .hint { color: #6b7280; font-size: 12px; padding: 6px 12px; }
  </style>
  <script>
    // Production: hide securityJsCode behind reverse proxy
    // Point AMap service calls to same-origin path handled by Nginx
    // window._AMapSecurityConfig = { serviceHost: '/_AMapService' };

    // For local quick test (no proxy): uncomment and set your securityJsCode (DO NOT use in production)
    window._AMapSecurityConfig = { securityJsCode: '90535a2ca9313ff3af940d4cb5947f36' };

    // Load AMap JS API with your public Key (Key must be whitelisted for your domain)
    const AMAP_KEY = '1276e82158171550ad98f4ef9567d8d8';
    (function loadAmap(){
      const s = document.createElement('script');
      s.src = 'https://webapi.amap.com/maps?v=2.0&key=' + encodeURIComponent(AMAP_KEY) + '&plugin=AMap.Scale,AMap.ToolBar,AMap.Geolocation,AMap.Driving,AMap.PlaceSearch';
      s.async = true; s.defer = true;
      s.onload = () => console.log('AMap SDK loaded');
      s.onerror = () => console.warn('Failed to load AMap SDK');
      document.head.appendChild(s);
    })();
  </script>
</head>
<body>
  <div id="app">
    <header>高德地图 JS API v2 Demo（代理隐藏安全密钥）</header>
    <div id="map"></div>
    <div class="toolbar">
      <button id="btnLocate">定位</button>
      <input id="from" size="24" placeholder="起点：如 杭州西湖" />
      <input id="to" size="24" placeholder="终点：如 黄山风景区" />
      <button id="btnRoute">驾车路线</button>
      <select id="policy">
        <option value="LEAST_TIME" selected>最快</option>
        <option value="LEAST_FEE">避免收费</option>
        <option value="LEAST_DISTANCE">最短</option>
        <option value="REAL_TRAFFIC">考虑实时路况</option>
      </select>
    </div>
    <div class="hint">
      生产环境应配置 Nginx 反向代理 <code>/_AMapService</code> 到 <code>https://restapi.amap.com</code> 并在代理端追加 <code>jscode</code>（安全密钥）。
      本页面仅演示 JS API 初始化、定位与驾车路线的基础用法。
    </div>
  </div>

  <script>
    let map, driving, placeSearch;
    let overlays = [];

    function initMapWhenReady() {
      if (!window.AMap) return void setTimeout(initMapWhenReady, 120);
      map = new AMap.Map('map', { viewMode: '2D', zoom: 11 });
      try { map.addControl(new AMap.ToolBar()); map.addControl(new AMap.Scale()); } catch {}
      driving = new AMap.Driving({ map, policy: AMap.DrivingPolicy.LEAST_TIME });
      placeSearch = new AMap.PlaceSearch({ city: '全国' });
    }
    initMapWhenReady();

    function clearOverlays() {
      try { overlays.forEach(o => map.remove(o)); overlays = []; } catch {}
      try { driving && driving.clear(); } catch {}
    }

    async function locate() {
      try {
        await new Promise((resolve, reject) => {
          AMap.plugin('AMap.Geolocation', function(){
            const geo = new AMap.Geolocation({ enableHighAccuracy: true, timeout: 3000, showCircle: true, showMarker: true, panToLocation: true, zoomToAccuracy: true });
            geo.getCurrentPosition((status, res) => { status === 'complete' ? resolve(res) : reject(res); });
          });
        });
      } catch (_) {
        alert('定位失败：请检查 HTTPS 与浏览器定位权限');
      }
    }

    async function geocodeBySearch(q) {
      return new Promise((resolve, reject) => {
        placeSearch.search(q, (status, result) => {
          if (status === 'complete' && result && result.poiList && result.poiList.pois && result.poiList.pois.length) {
            const poi = result.poiList.pois[0];
            resolve({ name: poi.name, lnglat: poi.location });
          } else {
            reject(new Error('未找到地点：' + q));
          }
        });
      });
    }

    async function route() {
      if (!driving) return;
      const from = document.getElementById('from').value.trim();
      const to = document.getElementById('to').value.trim();
      const policySel = document.getElementById('policy').value;
      if (!from || !to) { alert('请输入起终点'); return; }
      clearOverlays();
      driving.setPolicy(AMap.DrivingPolicy[policySel] || AMap.DrivingPolicy.LEAST_TIME);
      try {
        const s = await geocodeBySearch(from);
        const d = await geocodeBySearch(to);
        driving.search(s.lnglat, d.lnglat, (status, result) => {
          if (status === 'complete') {
            // 已自动在地图上绘制。可按需读取总里程/时长：
            try {
              const route = result.routes && result.routes[0];
              if (route) {
                const km = (route.distance / 1000).toFixed(1);
                const h = (route.time / 3600).toFixed(2);
                console.log('总里程:', km, 'km; 预计:', h, '小时');
              }
            } catch {}
          } else {
            alert('驾车规划失败');
          }
        });
      } catch (e) {
        alert(e.message || '搜索失败');
      }
    }

    // Wire UI
    document.getElementById('btnLocate').addEventListener('click', locate);
    document.getElementById('btnRoute').addEventListener('click', route);
  </script>
</body>
</html>
